package com.leesche.zcsp.node.utils.wechatutils;

import com.leesche.zcsp.node.utils.CommonUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.web.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Jerry Chan
 * @version V1.0
 * @Title: node
 * @Package com.leesche.zcsp.node.utils.wechatutils
 * @Description:( 微信工具类 )
 * @date 2016年11月07日 20:03
 */
public class WechatUtil {

    private final static Logger logger = LoggerFactory
            .getLogger(WechatUtil.class);

    /**
     * @param accessToken  访问令牌
     * @param mediaid      媒体ID
     * @param savePath 服务器保存资源的路径
     * @return filePath 已下载到本地服务器的资源文件名称
     * @Title: downloadMedia
     * @Description: TODO(根据访问令牌，媒体ID向微信服务器获取资源并保存到服务器指定的位置上)
     * @author Jerry Chan
     * @date 2016-11-07 08:39:50
     */
    public static String downloadMedia(String accessToken, String mediaid,String savePath) {

        if (accessToken == null || "".equals(accessToken)) {
            return null;
        }
        if (mediaid == null || "".equals(mediaid)) {
            return null;
        }

        String filePath = null;

        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaid;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            String fileExt = CommonUtil.getFileExt(conn.getHeaderField("Content-Type"));
            String logoName = "/" + mediaid + fileExt;

            String webRootPath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME,savePath);

            /*String webRootPath = SessionManager.getContext().getRealPath(savePath);*/
            File logoFilePath = new File(webRootPath);
            if (!logoFilePath.exists()) {
                logoFilePath.mkdirs();
            }

            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(webRootPath + logoName));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
            fos.close();
            bis.close();
            conn.disconnect();
            filePath =  SessionManager.getWebServerURL() + savePath + logoName;
            System.out.println(filePath);
            //filePath =  savePath + logoName;
        } catch (MalformedURLException e) {
            filePath = null;
            e.printStackTrace();
            logger.error("Malformed URL Exception:", e.getMessage());
        } catch (IOException e) {
            filePath = null;
            e.printStackTrace();
            logger.error("IO Exception:", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            filePath = null;
            logger.error(e.getMessage());
        }

        return filePath;

    }

}
